package org.ykhl.handlers.dao;

import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.ModelAndView;
import org.ykhl.handlers.util.RequestCache;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Created by wcd on 2017/3/15.
 */
@Service
public class LongTimeAsyncCallService {
    private final int CorePoolSize = 4;
    private final int NeedSeconds = 3;
    private Random random = new Random();
    private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(CorePoolSize);

    public void runexecute(){
        scheduler.submit(run);
    }
       Runnable run =new Runnable() {
            public void run() {
                new LongTermTaskCallback() {
                    public void callback(Object result) {
                        ModelAndView mav = new ModelAndView("remotecalltask");
                        mav.addObject("result", result);
                        try {
                            final DeferredResult<ModelAndView> deferredResult = RequestCache.cache.get("test", new Callable<DeferredResult<ModelAndView>>() {
                                public DeferredResult<ModelAndView> call() throws Exception {
                                    return null;
                                }
                            });
                            if(null!=deferredResult){
                                Thread.sleep(3000);
                                deferredResult.setResult(mav);
                                System.out.println("异步调用执行完成, thread id is : " + Thread.currentThread().getId());

                            }
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }


                    }
                }.callback("result");
            };
        //System.out.println("初始化完成");
    };
}
